package uy.com.dino.samefile.loader;


import uy.com.dino.samefile.model.FileInfo;
import uy.com.dino.samefile.util.FileUtil;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.security.MessageDigest;

public class ProcessorImpl implements Processor {

    @Override
    public FileInfo process(File file) {
        FileInfo fileInfo = new FileInfo();
        String checkSum = this.getMD5Checksum(file);
        fileInfo.setHashCode(checkSum);
        fileInfo.setName(file.getName());
        fileInfo.setPath(file.getPath());
        fileInfo.setDescription(FileUtil.getFileExtension(file.getName()));
        return fileInfo;
    }


    private byte[] createChecksum(File file) throws
            Exception {
        InputStream fis = new FileInputStream(file);

        byte[] buffer = new byte[1024];
        MessageDigest complete = MessageDigest.getInstance("MD5");
        int numRead;
        do {
            numRead = fis.read(buffer);
            if (numRead > 0) {
                complete.update(buffer, 0, numRead);
            }
        } while (numRead != -1);
        fis.close();
        return complete.digest();
    }

    private String getMD5Checksum(File file) {
        String result = "";

        try {
            byte[] b = createChecksum(file);
            for (int i = 0; i < b.length; i++) {
                result +=
                        Integer.toString((b[i] & 0xff) + 0x100, 16).substring(1);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

}
